package com.qf.micrograss.grass.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qf.common.core.entity.GrassLike;
import com.qf.common.core.util.UserUtils;
import com.qf.common.redis.utils.RedisUtil;
import com.qf.micrograss.grass.mapper.GrassLikeMapper;
import com.qf.micrograss.grass.service.GrassLikeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Classname GrassLikeServiceImpl
 * @Description
 * @Date 2025-05-29 15:43
 * @Created by 老任与码
 */
@Service
public class GrassLikeServiceImpl implements GrassLikeService {
    @Resource
    private GrassLikeMapper grassLikeMapper;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public void like(Integer grassId) {
        Integer uid = UserUtils.getUid();

        String key = String.format("likeNum:%s", DateUtil.format(new Date(), "yyyyMMdd"));

        GrassLike grassLike = grassLikeMapper.selectOne(Wrappers.lambdaQuery(GrassLike.class)
                .eq(GrassLike::getGrassId, grassId)
                .eq(GrassLike::getUid, uid));
        // 没有点赞，增加点赞记录，否则，删除点赞记录
        if (grassLike == null) {
            grassLike = new GrassLike();
            grassLike.setGrassId(grassId);
            grassLike.setUid(uid);
            grassLikeMapper.insert(grassLike);

            redisUtil.incrCacheMapValue(key, grassId.toString(), 1);
        } else {
            grassLikeMapper.deleteById(grassLike.getId());
            redisUtil.incrCacheMapValue(key, grassId.toString(), -1);
        }
    }

    @Override
    public List<GrassLike> listByGrassIdsAndUid(List<Integer> ids, Integer uid) {
        // select * from grass_like where uid=xxx and grass_id in (1, 2, 3)
        return grassLikeMapper.selectList(Wrappers.lambdaQuery(GrassLike.class)
                .eq(GrassLike::getUid, uid)
                .in(GrassLike::getGrassId, ids));
    }
}
